#include "Win32Time.h"

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

namespace GenBen {
	
Win32Time::Win32Time()
{
	QueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency);
	QueryPerformanceCounter((LARGE_INTEGER*)&start_time);

	fps_limit = current_time_ms = 0;
	last_fps_update = fps = frames_drawn = 0;

	update();
}

Win32Time::~Win32Time()
{
}

string Win32Time::timeToString(uint time)
{
	char time_str[8];
	sprintf(time_str, "%02u:%02u", time / (1000 * 60), (time / 1000) % 60);
	return string(time_str);
}

void Win32Time::update()
{
	old_time_ms = current_time_ms;

	do
	{
		QueryPerformanceCounter((LARGE_INTEGER*)&current_time);
		current_time_ms = perfCounterToMs(current_time);
		d_time_ms = current_time_ms - old_time_ms;
	} while(fps_limit != 0 && d_time_ms < (1000 / fps_limit));

	time_scale = (float)d_time_ms / 1000.0f;
	if (last_fps_update + 1000 <= current_time_ms)
	{
		fps = frames_drawn;
		frames_drawn = 0;
		last_fps_update = current_time_ms;
	}
	frames_drawn++;
}

uint Win32Time::perfCounterToMs(uint64 time)
{
	return (uint)((time - start_time) * 1000ULL / perf_frequency);
}

} // namespace
